package com.daykw.douyin.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;

import com.daykw.douyin.config.NutzDaoConfig;
import com.daykw.douyin.http.HttpBase;
import com.daykw.douyin.model.VideoComment;
import com.daykw.douyin.model.VideoTask;
import com.daykw.douyin.utils.MD5Util;
import com.daykw.douyin.utils.RadomU;
import com.daykw.douyin.utils.SpringContextHolder;

public class VideoCmtThread extends Thread {

	private static Logger logger = Logger.getLogger(VideoCmtThread.class);

	@Override
	public void run() {
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");

		NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
		int m = RadomU.getInstance().getValue();
		String node = "1";
		int v = m % 6;

		if (v == 0) {
			node = "0";
		} else if (v == 1) {
			node = "1";
		} else if (v == 2) {
			node = "2";
		} else if (v == 3) {
			node = "3";
		} else if (v == 4) {
			node = "4";
		} else if (v == 4) {
			node = "5";
		}
		//.and("node", "=", node)
		List<VideoTask> tasks = dao.query(VideoTask.class, Cnd.where("cmt_status", "=", 0).and("uid", "is not", null)
				.limit(1, 10).desc("cmtby"));

		HttpBase http = new HttpBase();
		Map<String, String> headers = new HashMap<String, String>();
		// String cookie = dao.fetch("t_cookie", Cnd.where("name", "=",
		// "大斌")).getString("cookie");
		List<Record> cookies = dao.query("t_cookie", Cnd.wrap("WHERE status=1 "));

		for (VideoTask task : tasks) {
			int random = org.apache.commons.lang3.RandomUtils.nextInt(0, cookies.size());

			Record cookie = cookies.get(random);

			try {
				if (StringUtils.isNotEmpty(task.getUid())) {
					int page = 1;
					boolean b = true;
					page = task.getCmt_page();
					do {
						String c = cookie.getString("cookie");
						String cname = cookie.getString("name");
						headers.put("Cookie", c);
						String url = task.getCmt_url() + "&page=" + page;
						String html = http.get(url, headers);
						if (html.indexOf("没有更多内容") > 0) {
							b = false;
						} else {
							Document doc = Jsoup.parse(html);

							Elements items = doc.select("div.list-info-item");
							if (items.isEmpty()) {
								b = false;
								logger.info("评论内容为空：" + url);
							}
							for (Element item : items) {
								String img = item.select("div.item-head img").attr("src");
								String name = item.select("div.item-head span.name").text();
								String like = item.select("div.item-head div.g-count").text();
								String body = item.select("p.item-body").text();
								String time = item.select("p.item-time").text();

								VideoComment cmt = new VideoComment();
								String uuid = MD5Util.getMD5(
										task.getKw_id() + "-" + task.getUid() + "-" + name + "-" + body + "-" + time);
								cmt.setUuid(uuid);
								cmt.setKw_id(task.getKw_id());
								cmt.setUid(task.getUid());
								cmt.setImg(img);
								cmt.setLike_num(like);
								cmt.setNick_name(name);
								cmt.setContent(body);
								cmt.setCreate_time(new Date());
								cmt.setCmt_time(time);
								cmt.setCdate(Long.parseLong(fmt.format(new Date())));
								try {
									dao.fastInsert(cmt);
								} catch (Exception e) {
									logger.error("评论重复：" + uuid);
								}
							}
							logger.info("##########" + task.getUid() + "评论抓完,第" + page + "页,cookie:" + cname);
							page++;
						}
						Thread.sleep(3000);
						if (page > 5) {
							b = false;
						}
					} while (b);
					dao.update(VideoTask.class, Chain.make("cmt_status", 2).add("cmt_page", page),
							Cnd.where("kw_id", "=", task.getKw_id()));
				}
			} catch (Exception e) {
				dao.update(VideoTask.class, Chain.make("cmt_status", 3), Cnd.where("kw_id", "=", task.getKw_id()));
				logger.error("", e);
			}
		}

	}
}
